<?php

class calendar {

	private $endpoint = 'https://www.google.com/calendar/feeds';
	private $user_id = 'eomohssl9vmhvtrj8tarm0evb4%40group.calendar.google.com';
	private $magic_cookie = 'private-ac09e0346b3fc6fe63b70880c2d2727b';

	// queries google calendar and returns formatted jsonc result
	private function get_events($args) {
		$args = http_build_query($args);
		$json_url = "{$this->endpoint}/{$this->user_id}/{$this->magic_cookie}/full?alt=jsonc&$args";
		return json_decode(file_get_contents($json_url));
	}

	public function render() {
		// sets start-max to one month in the future, sets start-min to 15 days ago
		$args = array(
			'start-min' => date("Y-m-d", strtotime("today", time())),
			'start-max' => date("Y-m-d", strtotime("+60 days", time())),
			'orderby' => 'starttime',
			'sortorder' => 'a',
			'max-results' => '70'
		);
		$calendar_json = $this->get_events($args);
		
		if ($calendar_json->data->items) {
			foreach($calendar_json->data->items as $item) {
				$start_time = new DateTime($item->when['0']->start);
				$end_time = new DateTime($item->when['0']->end);
				$start_timestamp = $start_time->format('U');
				if ($start_timestamp < time()) {
					echo '<div class="post row past">';
				} else {
					echo '<div class="post row">';
				}
					echo '<div class="twocol">';
					echo '<p class="date"><span class="day">'.$start_time->format('l').' </span><span>'.$start_time->format('M d').'</span> '.$start_time->format('Y').'</p>';
					echo '</div>';
					echo '<div class="tencol last">';
					// echo "<h1><a href=\"{$item->alternateLink}\">{$item->title}</a></h1>";
					echo "<h1>{$item->title}</h1>";
					echo '<p>';
						echo 'from ' . $start_time->format("h:ia") . ' until ' . $end_time->format("h:ia");
						echo " &ndash; at {$item->location}";
					echo '</p>';
					if (!empty($item->details))
						echo "<p>{$item->details}</p>";
					echo '</div>';
				echo '</div>';
			}
		} else {
			echo '<div class="post row">';
				echo '<div class="twelvecol last">';
				echo "<h1>No events yet</h1>";
				echo '<p>Check back for updates. We\'ll keep this calendar updated with tastemakers related events. We promise.</p>';
				echo '</div>';
			echo '</div>';
		}
	}
}

?>